package com.hzw.code.fast.sys.service.impl;

import com.hzw.code.fast.sys.controller.args.SysMenuArgs;
import com.hzw.code.fast.sys.controller.args.SysMenuPageArgs;
import com.hzw.code.fast.sys.controller.args.SysMenuQueryArgs;
import com.hzw.code.fast.sys.dto.SysMenuDto;
import com.hzw.code.fast.sys.dto.page.SysMenuPageDto;
import com.hzw.code.fast.sys.entity.SysMenuEntity;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzw.code.fast.sys.mapper.SysMenuMapper;
import com.hzw.code.fast.sys.service.SysMenuService;
import com.hzw.code.common.utils.ActionException;
import com.hzw.code.common.utils.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;

import java.util.List;
import org.springframework.transaction.annotation.Transactional;

/**
 * 菜单（资源）表(SysMenu)业务层实现
 *
 * @author 胡汉三
 * @date 2020-05-20 14:24:34
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenuEntity> implements SysMenuService {
    private final SysMenuMapper mapper;


    @Override
    public void save(SysMenuArgs args) throws RuntimeException {
        SysMenuEntity entity = new SysMenuEntity();
        BeanUtils.copyProperties(args, entity);
        boolean result = super.save(entity);
        if (!result) {
            throw new ActionException(ResultCodeEnum.DATABASE_INSERT_ERROR);
        }
    }


    @Override
    public void updateById(SysMenuArgs args) throws RuntimeException {
        // 查询数据是否存在
        this.getById(args.getMenuId());
        // 更新数据
        SysMenuEntity entity = new SysMenuEntity();
        BeanUtils.copyProperties(args, entity);
        boolean result = super.updateById(entity);
        if (!result) {
            throw new ActionException(ResultCodeEnum.DATABASE_UPDATE_ERROR);
        }
    }


    @Override
    public List<SysMenuDto> selectListByModel(SysMenuQueryArgs args) throws RuntimeException {
        List<SysMenuDto> list = mapper.selectListByModel(args);
        if (list == null || list.isEmpty()) {
            throw new ActionException(ResultCodeEnum.DATABASE_NODATA);
        }
        return list;
    }


    @Override
    public IPage<SysMenuPageDto> page(SysMenuPageArgs args) throws RuntimeException {
        return mapper.page(args.getQueryPage(), args);
    }


    @Override
    public SysMenuDto getById(String id) throws RuntimeException {
        SysMenuEntity byId = super.getById(id);
        if (byId == null) {
            throw new ActionException(ResultCodeEnum.DATABASE_NODATA);
        }
        SysMenuDto dto = new SysMenuDto();
        BeanUtils.copyProperties(byId, dto);
        return dto;
    }

    @Override
    public List<String> getMenuByRoles(List<String> list) {
        return mapper.getMenuByRoles(list);
    }
}